package com.xxh.auth.config;


import com.xxh.auth.filter.ValidateCodeFilter;
import com.xxh.auth.handler.CustomAuthenticationFailureHandler;
import com.xxh.auth.service.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    CustomAuthenticationFailureHandler authenticationFailureHandler;


    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailServiceImpl();
    }


    //设置密码加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setFailureHandler(authenticationFailureHandler);

        http.csrf().disable()
                //新增验证码拦截逻辑
                .addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                //认证之后才可以获取属于用户自己的公钥
                .antMatchers("/user/**", "/getPublicKey").authenticated()
                .antMatchers("/fuck/**").hasAnyRole("man")
                .antMatchers("/login", "/oauth/token").permitAll();
//                .anyRequest().authenticated();

        //登录失败成功自定义处理器以及返回结果
        http.formLogin()
                .failureHandler(authenticationFailureHandler);


    }

    /**
     * 配置用户数据源和加密方式
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());

    }

    /**
     * 认证管理器
     *
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
